<template>
  <el-dialog
    v-model="dialogFormVisible"
    class="dialog-wrap"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <template #header>
      <div class="dialog-title">
        {{ title }}
      </div>
    </template>

    <el-form
      ref="ruleForm"
      class="ruleForm ruleForm-g2"
      :disabled="formDisabled"
      label-width="auto"
      :model="form"
      :rules="rules"
      style="max-width: 600px"
    >
      <el-form-item label="所属学院" prop="collegeId">
        <el-select
          v-model="form.collegeId"
          clearable
          placeholder="请选择所属学院"
          @change="form.professionId = null"
        >
          <el-option
            v-for="item in collegeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="所属系" prop="professionId">
        <el-select
          v-model="form.professionId"
          clearable
          placeholder="请选择所属系"
        >
          <el-option
            v-for="item in professionOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="班级年份" prop="grade">
        <el-date-picker
          v-model="form.grade"
          placeholder="请选择班级年份"
          type="year"
          value-format="YYYY"
        />
      </el-form-item>

      <el-form-item label="班级名称" prop="className">
        <el-input
          v-model.trim="form.className"
          maxlength="20"
          placeholder="请输入班级名称"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="培养层次" prop="dictCultivationLevel">
        <el-select
          v-model="form.dictCultivationLevel"
          clearable
          placeholder="请选择培养层次"
        >
          <el-option
            v-for="dict in dict.cultivation_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="班级代码" prop="classCode">
        <el-input
          v-model.trim="form.classCode"
          maxlength="20"
          placeholder="请输入班级代码"
          show-word-limit
        />
      </el-form-item>

      <el-form-item class="column-all" label="备注信息" prop="note">
        <el-input
          v-model.trim="form.note"
          maxlength="300"
          placeholder="填写班级备注信息（非必填）"
          rows="6"
          show-word-limit
          type="textarea"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>

        <el-button
          v-if="loadType != 'detail'"
          v-loading="loading"
          type="primary"
          @click="submitForm"
        >
          确 定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
  import $api from './api.js'

  // 院,系,班级 级联数据
  import { createCollegeData } from '@/utils/college-cascader.js'

  export default {
    emits: ['save'],
    data() {
      return {
        dialogFormVisible: false,
        loadType: 'add',
        title: '',
        formDisabled: false,
        loading: false,

        def: {
          id: null,
          collegeId: '',
          professionId: '',
          grade: '',
          className: '',
          classCode: '',
          note: '',
          dictCultivationLevel: '',
        },

        form: {},

        rules: {
          collegeId: [
            { required: true, message: '所属学院不能为空', trigger: 'blur' },
          ],

          professionId: [
            { required: true, message: '所属系不能为空', trigger: 'blur' },
          ],

          grade: [
            { required: true, message: '班级年份不能为空', trigger: 'blur' },
          ],

          className: [
            { required: true, message: '班级名称不能为空', trigger: 'blur' },
          ],

          dictCultivationLevel: [
            { required: true, message: '培养层次不能为空', trigger: 'blur' },
          ],

          classCode: [
            { min: 0, max: 20, message: '长度应为0~20个字符', trigger: 'blur' },
            {
              message: '只能填写字母、数字和“-”',
              trigger: 'blur',
              validator: (rule, value, callback) => {
                const reg = /^[a-zA-Z0-9\-]+$/
                if (!value) {
                  callback()
                  return
                }
                if (reg.test(value)) {
                  callback()
                } else {
                  callback(new Error(rule.message))
                }
              },
            },
          ],

          note: [
            {
              min: 0,
              max: 300,
              message: '长度应为0~300个字符',
              trigger: 'blur',
            },
          ],
        },

        dict: {},

        collegeOptions: [],
        professionOptions: [],
        classOptions: [],
      }
    },

    created() {
      // init Data

      // 设置院,系,班级 级联数据
      const {
        collegeId,
        professionId,
        classId,
        collegeOptions,
        professionOptions,
        classOptions,
      } = createCollegeData()
      this.form.collegeId = collegeId
      this.form.professionId = professionId
      this.form.classId = classId
      this.collegeOptions = collegeOptions
      this.professionOptions = professionOptions
      this.classOptions = classOptions

      // 静态字典
      const dictMap = ['cultivation_level']
      const dictList = this.useDict(dictMap)

      for (let f1 in dictList) {
        this.dict[f1] = dictList[f1]
      }
    },

    methods: {
      load(type, d) {
        this.dialogFormVisible = true
        this.reset()

        const titleStr = '班级信息'
        this.loadType = type

        if (this.loadType === 'detail') {
          this.formDisabled = true
          this.title = `查看${titleStr}`
          for (let f1 in d) {
            this.form[f1] = d[f1]
          }
        }

        if (this.loadType === 'add') {
          this.title = `添加${titleStr}`
        }

        if (this.loadType === 'edit') {
          this.title = `修改${titleStr}`
          for (let f1 in d) {
            this.form[f1] = d[f1]
          }
        }
      },

      reset() {
        this.formDisabled = false
        if (this.ruleForm) {
          this.ruleForm.resetFields()
        }
        const d = Object.assign({}, this.def)
        for (let f1 in d) {
          this.form[f1] = d[f1]
        }
      },

      submitForm() {
        this.$refs.ruleForm.validate((valid, fields) => {
          if (valid) {
            if (this.loadType === 'add') {
              this.add()
            }

            if (this.loadType === 'edit') {
              this.edit()
            }
          }
        })
      },

      add() {
        const sendData = {
          ...this.form,
        }
        this.loading = true
        $api
          .add(sendData)
          .then((res) => {
            this.$message.success('新增成功')
            this.$emit('save')
            this.dialogFormVisible = false
          })
          .finally(() => {
            this.loading = false
          })
      },

      edit() {
        const sendData = {
          ...this.form,
        }

        this.loading = true
        $api
          .edit(sendData)
          .then((res) => {
            this.$message.success('修改成功')
            this.$emit('save')
            this.dialogFormVisible = false
          })
          .finally(() => {
            this.loading = false
          })
      },
    },
  }
</script>

<style lang="scss" scoped></style>
